<script setup lang="ts">
import {
  getAllAcademy,
  addAcademy,
  updateAcademy,
  deleteAcademy,
  getAcademyByPage
} from "@/api/index";
import { ref, onMounted, reactive, watch } from "vue";
import type { TreeNode } from "@/types/common";
import {
  ElTable,
  ElTableColumn,
  ElTag,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElCard,
  ElTree,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadioButton
} from "element-plus";

interface AcademyData {
  id: number;
  oid: string;
  zh_name: string;
  pid: string;
  class_id: number;
  class_name: string;
  seqnum_id: number | null;
  is_valid: number;
}

interface AddInstitutionForm {
  oid: string;
  pid: string;
  zh_name: string;
  class_id: number;
  class_name: string;
}

interface UpdateAcademyForm {
  id: number;
  oid?: string;
  zh_name?: string;
  pid?: string;
  class_name?: string;
  seqnum_id?: string;
  is_vaild?: number;
}

interface AddAcademyForm {
  oid: string;
  zh_name: string;
  pid: string;
  class_id: number;
  class_name: string;
}

const tableData = ref<TreeNode[]>([]);
const expandRowKeys = ref<string[]>([]);
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const formData = reactive<AddAcademyForm>({
  oid: "",
  zh_name: "",
  pid: "",
  class_id: 3,
  class_name: ""
});
const editFormData = reactive<UpdateAcademyForm>({
  id: 0,
  oid: "",
  zh_name: "",
  pid: "",
  class_name: "",
  seqnum_id: "",
  is_vaild: 1
});
const currentRow = ref<TreeNode | null>(null);
const viewType = ref("tree"); // 视图类型：tree 或 table
const tableLoading = ref(false);
const pagination = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15
});
const searchForm = reactive({
  id: "",
  oid: "",
  zh_name: "",
  class_id: ""
});

// 添加类型选项常量
const typeOptions = [
  { value: 1, label: "学校", class_name: "学校" },
  { value: 2, label: "学院", class_name: "学院" },
  { value: 3, label: "专业", class_name: "专业" },
  { value: 4, label: "班级", class_name: "班级" }
];

// 将扁平数据转换为树形结构
const convertToTreeData = (data: AcademyData[]): TreeNode[] => {
  const map = new Map();
  const result: TreeNode[] = [];

  // 先创建一个以oid为键的映射
  data.forEach(item => {
    map.set(item.oid, {
      id: item.id,
      label: item.zh_name,
      children: [],
      ...item
    });
  });

  // 构建树形结构
  data.forEach(item => {
    const node = map.get(item.oid);
    if (item.pid === "-1") {
      // 根节点
      result.push(node);
      // 将一级机构的ID转换为字符串后添加到展开行列表中
      expandRowKeys.value.push(String(node.id));
    } else {
      // 子节点
      const parent = map.get(item.pid);
      if (parent) {
        parent.children.push(node);
      }
    }
  });

  return result;
};

// 获取学院数据
const loadAcademyData = async () => {
  try {
    const response = await getAllAcademy();
    if (response.status === "success" && response.data) {
      tableData.value = convertToTreeData(response.data);
    }
  } catch (error) {
    console.error("获取学院数据失败:", error);
  }
};

// 获取表格数据
const loadTableData = async () => {
  try {
    tableLoading.value = true;
    const response = await getAcademyByPage({
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    });
    if (response.status === "success" && response.data) {
      tableData.value = response.data.records;
      pagination.total = response.data.pagination.total;
    }
  } catch (error) {
    console.error("获取表格数据失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    tableLoading.value = false;
  }
};

// 处理修改按钮点击
const handleEdit = (row: TreeNode) => {
  // 填充表单数据
  editFormData.id = row.id;
  editFormData.oid = row.oid;
  editFormData.zh_name = row.zh_name;
  editFormData.pid = row.pid;
  editFormData.class_name = row.class_name;
  editFormData.seqnum_id = row.seqnum_id?.toString() || "";
  editFormData.is_vaild = row.is_valid;
  editDialogVisible.value = true;
};

// 处理删除按钮点击
const handleDelete = (row: TreeNode) => {
  ElMessageBox.confirm(`确认删除"${row.zh_name}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await deleteAcademy(row.id);
        if (response.status === "success") {
          ElMessage.success("删除成功");
          // 重新加载数据
          await loadAcademyData();
        } else {
          ElMessage.error(response.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 用户取消删除操作
    });
};

// 修改handleAddChild函数
const handleAddChild = (row: TreeNode) => {
  currentRow.value = row;
  formData.oid = "";
  formData.pid = row.oid; // 设置默认值，但允许修改
  formData.zh_name = "";
  formData.class_id = row.class_id + 1 > 4 ? 4 : row.class_id + 1; // 设置下一级类型
  const selectedType = typeOptions.find(
    option => option.value === formData.class_id
  );
  if (selectedType) {
    formData.class_name = selectedType.class_name;
  }
  dialogVisible.value = true;
};

// 处理类型选择变化
const handleTypeChange = (value: number) => {
  const selectedType = typeOptions.find(option => option.value === value);
  if (selectedType) {
    formData.class_name = selectedType.class_name;
  }
};

// 修改handleAdd函数
const handleAdd = () => {
  formData.oid = "";
  formData.pid = ""; // 清空父级ID，允许用户输入
  formData.zh_name = "";
  formData.class_id = 1;
  formData.class_name = "学校";
  dialogVisible.value = true;
};

// 修改提交表单验证
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!formData.zh_name.trim()) {
      ElMessage.warning("名称不能为空");
      return;
    }
    if (!formData.oid.trim()) {
      ElMessage.warning("机构ID不能为空");
      return;
    }
    if (!formData.class_name.trim()) {
      ElMessage.warning("类型名称不能为空");
      return;
    }

    const requestBody: AddAcademyForm = {
      oid: formData.oid,
      zh_name: formData.zh_name,
      pid: formData.pid || "-1", // 如果未填写父级ID，则默认为根节点
      class_id: formData.class_id,
      class_name: formData.class_name
    };

    const response = await addAcademy(requestBody);
    if (response.status === "success") {
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      // 根据当前视图类型重新加载数据
      if (viewType.value === "table") {
        await loadTableData();
      } else {
        await loadAcademyData();
      }
      // 展开父节点（仅在树形视图中）
      if (
        viewType.value === "tree" &&
        currentRow.value &&
        !expandRowKeys.value.includes(String(currentRow.value.id))
      ) {
        expandRowKeys.value.push(String(currentRow.value.id));
      }
    } else {
      ElMessage.error("添加失败");
    }
  } catch (error) {
    console.error("添加失败:", error);
    ElMessage.error("添加失败");
  }
};

// 提交修改表单
const handleEditSubmit = async () => {
  try {
    // 表单验证
    if (!editFormData.zh_name.trim()) {
      ElMessage.warning("名称不能为空");
      return;
    }
    if (!editFormData.oid.toString().trim()) {
      ElMessage.warning("机构ID不能为空");
      return;
    }
    if (!editFormData.class_name.trim()) {
      ElMessage.warning("类型名称不能为空");
      return;
    }

    const requestBody: UpdateAcademyForm = {
      id: editFormData.id,
      oid: editFormData.oid,
      zh_name: editFormData.zh_name,
      pid: editFormData.pid,
      class_name: editFormData.class_name,
      seqnum_id: editFormData.seqnum_id,
      is_vaild: editFormData.is_vaild
    };

    const response = await updateAcademy(requestBody);
    if (response.status === "success") {
      ElMessage.success("修改成功");
      editDialogVisible.value = false;
      // 重新加载数据
      await loadAcademyData();
    } else {
      ElMessage.error("修改失败");
    }
  } catch (error) {
    console.error("修改失败:", error);
    ElMessage.error("修改失败");
  }
};

// 根据class_id获取对应的class_name
const getClassNameByClassId = (classId: number): string => {
  switch (classId) {
    case 1:
      return "学校";
    case 2:
      return "学院";
    case 3:
      return "专业";
    case 4:
      return "班级";
    default:
      return "未知";
  }
};

// 处理页码变化
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  loadTableData();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadTableData();
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadTableData();
};

// 处理重置搜索
const handleReset = () => {
  searchForm.id = "";
  searchForm.oid = "";
  searchForm.zh_name = "";
  searchForm.class_id = "";
  pagination.currentPage = 1;
  loadTableData();
};

// 监听视图类型变化
watch(viewType, newVal => {
  if (newVal === "table") {
    loadTableData();
  } else {
    loadAcademyData();
  }
});

onMounted(() => {
  loadAcademyData();
});
</script>

<template>
  <div class="academy-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="header-title">河南农业大学学院管理</span>
          <el-radio-group v-model="viewType" size="small">
            <el-radio-button label="tree">树形视图</el-radio-button>
            <el-radio-button label="table">表格视图</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <div v-if="viewType === 'tree'">
        <el-tree
          :data="tableData"
          :props="{
            children: 'children',
            label: 'zh_name'
          }"
          node-key="id"
          :default-expanded-keys="expandRowKeys"
          :expand-on-click-node="false"
        >
          <template #default="{ data }">
            <div class="custom-tree-node">
              <div class="node-content">
                <span class="node-id">{{ data.oid }}</span>
                <span class="node-name">{{ data.zh_name }}</span>
                <span
                  class="node-type"
                  :class="{
                    'type-school': data.class_id === 1,
                    'type-college': data.class_id === 2,
                    'type-major': data.class_id === 3,
                    'type-class': data.class_id === 4
                  }"
                >
                  {{ data.class_name }}
                </span>
              </div>
              <div class="operation-group">
                <el-tag
                  type="primary"
                  class="operation-tag"
                  effect="light"
                  @click="handleEdit(data)"
                >
                  修改
                </el-tag>
                <el-tag
                  type="danger"
                  class="operation-tag"
                  effect="light"
                  @click="handleDelete(data)"
                >
                  删除
                </el-tag>
                <el-tag
                  type="success"
                  class="operation-tag"
                  effect="light"
                  @click="handleAddChild(data)"
                >
                  新增
                </el-tag>
              </div>
            </div>
          </template>
        </el-tree>
      </div>

      <div v-else>
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="ID">
            <el-input
              v-model="searchForm.id"
              placeholder="请输入ID"
              clearable
            />
          </el-form-item>
          <el-form-item label="机构ID">
            <el-input
              v-model="searchForm.oid"
              placeholder="请输入机构ID"
              clearable
            />
          </el-form-item>
          <el-form-item label="名称">
            <el-input
              v-model="searchForm.zh_name"
              placeholder="请输入名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="searchForm.class_id"
              placeholder="请选择类型"
              clearable
              style="width: 100px"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="oid" label="机构ID" width="120" />
          <el-table-column prop="zh_name" label="名称" />
          <el-table-column prop="pid" label="父级ID" width="120" />
          <el-table-column prop="class_name" label="类型" width="100">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.class_id === 1
                    ? 'primary'
                    : row.class_id === 2
                      ? 'success'
                      : row.class_id === 3
                        ? 'warning'
                        : 'info'
                "
              >
                {{ row.class_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="is_valid" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.is_valid === 1 ? 'success' : 'danger'">
                {{ row.is_valid === 1 ? "有效" : "无效" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">
                修改
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[15, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增子机构弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增子机构"
      width="500px"
      destroy-on-close
    >
      <el-form :model="formData" label-width="100px" class="institution-form">
        <el-form-item label="机构ID" required>
          <el-input v-model="formData.oid" placeholder="请输入机构ID" />
        </el-form-item>
        <el-form-item label="名称" required>
          <el-input v-model="formData.zh_name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="父级ID">
          <el-input
            v-model="formData.pid"
            placeholder="请输入父级ID，不填则为根节点"
          />
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select
            v-model="formData.class_id"
            placeholder="请选择分类"
            @change="handleTypeChange"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改机构弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改机构"
      width="500px"
      destroy-on-close
    >
      <el-form
        :model="editFormData"
        label-width="100px"
        class="institution-form"
      >
        <el-form-item label="ID" required>
          <el-input v-model="editFormData.id" type="number" disabled />
        </el-form-item>
        <el-form-item label="机构ID" required>
          <el-input v-model="editFormData.oid" placeholder="请输入机构ID" />
        </el-form-item>
        <el-form-item label="机构名称" required>
          <el-input
            v-model="editFormData.zh_name"
            placeholder="请输入机构名称"
          />
        </el-form-item>
        <el-form-item label="父级ID" required>
          <el-input v-model="editFormData.pid" placeholder="请输入父级ID" />
        </el-form-item>
        <el-form-item label="类型ID" required>
          <el-input
            v-model="editFormData.class_name"
            placeholder="请输入类型名称"
          />
        </el-form-item>
        <el-form-item label="序号ID">
          <el-input
            v-model="editFormData.seqnum_id"
            type="number"
            placeholder="请输入序号ID"
          />
        </el-form-item>
        <el-form-item label="是否有效" required>
          <el-input
            v-model="editFormData.is_vaild"
            type="number"
            placeholder="请输入是否有效"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.academy-container {
  height: 100%;
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .header-title {
    font-size: 18px;
    font-weight: bold;
  }
}

.field-description {
  padding: 15px;
  margin-bottom: 20px;
  background-color: #fafafa;
  border-radius: 4px;

  .field-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .field-label {
    width: 100px;
    font-weight: bold;
    color: #606266;
  }

  .field-example {
    font-family: monospace;
    color: #909399;
  }

  .type-examples {
    display: flex;
    gap: 10px;
    align-items: center;

    .node-type {
      padding: 2px 6px;
      font-size: 12px;
      border-radius: 4px;
    }
  }
}

:deep(.custom-tree-node) {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;

  .node-content {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .node-id {
    font-family: monospace;
  }

  .node-type {
    padding: 2px 6px;
    font-size: 12px;
    border-radius: 4px;

    &.type-school {
      color: #1890ff;
      background-color: #e6f7ff;
    }

    &.type-college {
      color: #52c41a;
      background-color: #f6ffed;
    }

    &.type-major {
      color: #faad14;
      background-color: #fff7e6;
    }

    &.type-class {
      color: #606266;
      background-color: #f0f0f0;
    }
  }

  .operation-group {
    display: flex;
    gap: 8px;
  }
}

:deep(.el-tree-node) {
  .el-tree-node__content {
    height: 40px;
  }
}

.operation-tag {
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    opacity: 0.8;
  }
}

.institution-form {
  padding: 20px;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-form-item.is-required .el-form-item__label::before) {
    color: var(--el-color-danger);
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.el-select) {
  width: 100%;
}

.search-form {
  padding: 20px;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
